import {noLoadingRequest} from "../utils/request"

//新增动态
/**
 * @param {String} message //动态信息文字
 * @param {Array} images //动态图片
 * @param {Array} dynamicTag // 动态标签
 */
export const addDynamic = async function (params) {
  let uploadImgArr = []
  wx.showLoading({
    title: '正在提交',
  })
  params.images.forEach(item => {
    uploadImgArr.push(new Promise((reslove, reject) => {
      wx.cloud.uploadFile({
        cloudPath: `dynamic/${Date.now()}-${Math.floor(Math.random(0, 1) * 1000)}` + item.match(/\.[^.]+?$/),
        filePath: item, // 文件路径
      }).then(res => {
        reslove(res.fileID)
      }).catch(err => {
        reject(err)
      })
    }))
  })
  const imagesResult = await Promise.all(uploadImgArr)
  params.images = imagesResult
  const {
    result
  } = await wx.cloud.callFunction({
    name: "dynamic",
    data: {
      api: "add_dynamic",
      data: params
    }
  })
  wx.hideLoading()
  return result.data
}

//动态列表
/**
 * @param {Number} page //当前页
 * @param {Number} number //每页数量
 */
export const dynamicList = async function(params){
  const userInfo = wx.getStorageSync('wjUser')
  const header = {
    name:"dynamic",
    api:"dynamic_list",
    isUser:false
  }
  if(userInfo._openid){
    header.isUser = true
  }
  const result = await noLoadingRequest(header,params)
  return result.data
}

//动态详情
/**
 * @param {String} dynamicId //动态id
 */
export const dynamicDetail = async function(params){
  wx.showLoading({
    title: '正在加载...',
  })
  const {result} = await wx.cloud.callFunction({
    name:"dynamic",
    data:{
      api:"dynamic_detail",
      data:params
    }
  })
  wx.hideLoading()
  return result.data
}
//发布动态评论
/**
 * @param {String} dynamicId //动态id
 * @param {String} message //评论内容
 * @param {Array}  images  //评论图片(暂时不做)
 * 
 */
export const dynamicComment = async function(params){
  const {result} = await wx.cloud.callFunction({
    name:"dynamic",
    data:{
      api:"dynamic_comment",
      data:params
    }
  })
  return result.data
}
//动态的点赞接口
/**
 * @param {String} dynamicId //动态id
 * @param {Number} active //是否点赞 0 否 1 是
 */
export const dynamicEndorse = async function(params){
  const header={
    name:"dynamic",
    api:"dynamic_endorse",
    isUser:true
  }
  const result = await noLoadingRequest(header,params)
  return result.data
}
//用户个人发布的动态列表
/**
 * @param {Number} page //当前页
 * @param {Number} number //每页数量
 */
export const userDynamicList = async function(params){
  const header = {
    name:"dynamic",
    api:"dynamic_user",
    isUser:true
  }
  const result = await noLoadingRequest(header,params)
  return result.data
}


// 查询所有动态的标签
export const dynamicTag = async function (params) {
  let data = {
    api: 'dynamicTag',
    data: params,
  }
  const {
    result
  } = await wx.cloud.callFunction({
    data,
    name: 'dynamic'
  })

  return result.data
}